<template>
  <div>
    <van-nav-bar title="统计" fixed />
    <div id="lineChart" style="width: 400px; height: 300px"></div>
    <div id="pieChart" style="width: 400px; height: 300px"></div>
  </div>
</template>

<script>
const AV = require("leancloud-storage");
const { Query } = AV;
export default {
  data() {
    return {
      typeArr: [],
      pieData: [],
      lineData: [],
    };
  },
  async mounted() {
    await this.getAllData();
    this.drawLine();
  },
  methods: {
    drawLine() {
      // 基于准备好的dom，初始化echarts实例
      let lineChart = this.$echarts.init(document.getElementById("lineChart"));
      // 绘制图表
      lineChart.setOption({
        title: { text: "一周新增数量" },
        tooltip: {},
        xAxis: {
          type: "category",
          data: ["周一", "周二", "周三", "周四", "周五", "周六", "周末"],
        },
        yAxis: {
          type: "value",
        },
        series: [
          {
            name: "记录数量",
            type: "line",
            data: [...this.lineData],
          },
        ],
      });
      let pieChart = this.$echarts.init(document.getElementById("pieChart"));
      let option = {
        title: { text: "物品分类" },
        series: [
          {
            name: "分类占比",
            type: "pie",
            data: [...this.pieData],
            radius: "50%",
            center: ["50%", "50%"],
            label: {
              normal: {
                formatter: "{b}:{c}: ({d}%)",
                textStyle: {
                  fontWeight: "normal",
                  fontSize: 12,
                },
              },
            },
            itemStyle: {
              emphasis: {
                shadowBlur: 10,
                shadowOffsetX: 0,
                shadowColor: "rgba(0, 0, 0, 0.5)",
              },
            },
          },
        ],
      };
      pieChart.setOption(option);
    },
    calculateArrNum(arr) {
      var countedArr = arr.reduce((obj, name) => {
        if (name in obj) {
          obj[name]++;
        } else {
          obj[name] = 1;
        }
        return obj;
      }, {});
      return countedArr;
    },
    async getAllData() {
      const query = new AV.Query("FoodPeriod");
      let res = await query.find();
      let weekArr = [];
      res.forEach((item) => {
        weekArr.push(item.createdAt.getDay());
        this.typeArr.push(item.attributes.Type);
      });
      console.log(weekArr);
      let weekObj = this.calculateArrNum(weekArr);
      for (const key in weekObj) {
        this.lineData[key - 1] = weekObj[key];
      }
      console.log(this.lineData);
      let obj = this.calculateArrNum(this.typeArr);
      for (const key in obj) {
        let typeData = {
          name: key,
          value: obj[key],
        };
        this.pieData.push(typeData);
      }
    },
  },
};
</script>

<style>
#lineChart{
  margin: 5% auto 0 auto;
}
#pieChart {
  margin: 30px auto;
}
</style>
